/*
 * @Description: file content
 * @Author: RongWei
 * @Date: 2019-11-05 11:15:04
 * @LastEditors: RongWei
 * @LastEditTime: 2020-09-23 19:47:00
 */
import i18n from 'i18next';
import { initReactI18next } from "react-i18next";
import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
const localStorage = window.localStorage;
let p;
function loadLang(lang) {
    const resources = { zh: {}, en: {} };

    p = new Promise((resolve, reject) => {
        Promise.all([
            import(`@maycur/business/lib/lang/${lang}`).then(module => module.default)
        ]).then(res => {
            resources[lang] = { ...res[0] };
            resolve(resources);
        }).catch(e => {
            reject(e);
        });
    });
    return p;
}

const detection = {
    order: ['localStorage', 'navigator'],
    lookupLocalStorage: 'lang',
    caches: ['localStorage']
};

async function init() {
    if (localStorage.getItem('lang') === 'en') {
        document.title = "Maycur Expense";
    }
    return i18n
        //.use(Backend)
        .use(LanguageDetector)
        .use(initReactI18next)
        .init({
            ns: ['Global', 'ApproverCategory'],
            defaultNS: 'Global', // 默认的命名空间
            resources: {},
            fallbackLng: {
                'zh-CN': ['zh'],
                'en-US': ['en'],
                'default': ['zh', 'en']
            },
            //backend: { loadPath: 'locales/{{lng}}/{{ns}}.json' },
            detection,
            load: 'languageOnly',
            interpolation: {
                escapeValue: false
            },
            debug: false,
            saveMissing: false,
            partialBundledLanguages: true,
            parseMissingKeyHandler: () => '...',
            react: {
                useSuspense: false,
                wait: true
            }
        },  async () => {
            let lang = localStorage.getItem('lang') || 'zh';
            lang = lang.startsWith('zh') ? 'zh' : 'en';
            const resources = await loadLang(lang);
            Object.keys(resources[lang]).forEach((namespace) => {
                i18n.addResourceBundle(lang, namespace, resources[lang][namespace]);
            });
            i18n.changeLanguage(lang);
        }).then(() => {
            let i18nLanguage = i18n.language || 'zh';
            i18nLanguage = i18nLanguage.startsWith('zh') ? 'zh' : 'en';
            window.maycurConfig = { language: i18nLanguage };
            localStorage.setItem('lang', i18nLanguage);
            return p;
        });
}
export default {
    init
};